package com.qkl.xiatang.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qkl.xiatang.app.dto.BusinessDTO;
import com.qkl.xiatang.app.dto.PageOutDTO;
import com.qkl.xiatang.app.dto.user.*;
import com.qkl.xiatang.app.entity.CompanyEntity;
import com.qkl.xiatang.app.entity.user.AppUserApplyCompany;
import com.qkl.xiatang.app.entity.user.AppUserCompanyEntity;
import com.qkl.xiatang.app.entity.user.AppUserInfo;
import com.qkl.xiatang.app.mapper.AppUserApplyCompanyMapper;
import com.qkl.xiatang.app.mapper.AppUserCompanyMapper;
import com.qkl.xiatang.app.mapper.AppUserInfoMapper;
import com.qkl.xiatang.app.mapper.CompanyMapper;
import com.qkl.xiatang.app.utils.AppSessionUtils;
import com.qkl.xiatang.app.utils.appenum.AppUserDutiesEnum;
import com.qkl.xiatang.app.utils.appenum.AppUserStatus;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AppUserManagerService {

    @Autowired
    private AppUserInfoMapper userInfoMapper;

    @Autowired
    private AppUserCompanyMapper appUserCompanyMapper;

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private AppUserApplyCompanyMapper appUserApplyCompanyMapper;


    @Autowired
    private AppUserIdentityService appUserIdentityService;

    /**
     * 职位列表
     * @param userId
     * @return
     */
    public BusinessDTO<Object> userDutiesList(String userId){
        String companyId = AppSessionUtils.getCompanyId();
        List<UserDutiesDTO> dutiesList = AppUserDutiesEnum.dutiesList();

        /**
        if(StringUtils.isNotEmpty(userId)){
            List<AppUserCompanyEntity> userCompanyList = appUserCompanyMapper.selectList(new QueryWrapper<AppUserCompanyEntity>().eq("company_id",companyId).eq("app_user_id",userId));
            if(ObjectUtils.isNotEmpty(userCompanyList)){
                String identity  = userCompanyList.get(0).getIdentity();
                if(StringUtils.isNotEmpty(identity)) {
                    for (UserDutiesDTO dto : dutiesList) {
                        if (AppUserDutiesEnum.isDuties(dto.getType(),identity)){
                            dto.setUserDuties(true);
                        }
                    }
                }
            }
        }
         **/


        if(StringUtils.isNotEmpty(userId)){
            Set<String> identitySet = appUserIdentityService.queryUserIdentitySet(companyId,userId);
            if(ObjectUtils.isNotEmpty(identitySet)){
                for (UserDutiesDTO dto : dutiesList) {
                    if (identitySet.contains(dto.getType())){
                        dto.setUserDuties(true);
                    }
                }
            }
        }

        Map<String,Object> map = new HashMap<>();
        map.put("dutiesList",dutiesList);
        return BusinessDTO.sucessBusiness(map,"职位列表");
    }

    /**
     * 查询申请用户
     * @param webDTO
     * @return
     */
    public BusinessDTO<Object> queryApplyUser(UserQueryInDTO webDTO){
        webDTO.setStatus(0);
        return this.queryApplyUserList(webDTO);
    }

    /**
     * 查询正常用户
     * @param webDTO
     * @return
     */
    public BusinessDTO<Object> queryNormalUser(UserQueryInDTO webDTO){
        webDTO.setStatus(1);
        return this.queryApplyUserList(webDTO);
    }

    /**
     * 用户申请加入公司
     * @param webDTO
     * @return
     */
    public BusinessDTO<Object> userApplyCompany(UserApplyWebDTO webDTO){
        if( !AppSessionUtils.statusOK()){
            return BusinessDTO.failBusiness("用户未审核");
        }
        String applyCompanyId = StringUtils.trimToEmpty(webDTO.getCompanyId());
        if(StringUtils.isEmpty(applyCompanyId)){
            return BusinessDTO.failBusiness("未选择公司");
        }
        CompanyEntity companyEntity = companyMapper.selectById(applyCompanyId);
        if(null ==companyEntity){
            return BusinessDTO.failBusiness("公司不存在");
        }
        String userId = AppSessionUtils.getUserId();
        List<AppUserCompanyEntity> userCompanyList = this.queryUserCompany(applyCompanyId,userId);
        if(ObjectUtils.isNotEmpty(userCompanyList)){
            return BusinessDTO.failBusiness("您已加入公司，无需申请");
        }
        if( ObjectUtils.isNotEmpty(appUserApplyCompanyMapper.selectList(new QueryWrapper<AppUserApplyCompany>().eq("company_id",applyCompanyId).eq("app_user_id",userId)))){
            return BusinessDTO.failBusiness("匆重复申请公司");
        }
        AppUserApplyCompany  applyCompany = new AppUserApplyCompany();
        applyCompany.setCompanyId(applyCompanyId);
        applyCompany.setAppUserId(userId);
        appUserApplyCompanyMapper.insert(applyCompany);
        return BusinessDTO.sucessBusiness(new HashMap<>(),"申请加入公司");
    }

    /**
     * 用户取消加入公司申请
     * @param webDTO
     * @return
     */
    public BusinessDTO<Object> userApplyCompanyUndo(UserApplyWebDTO webDTO){
        if( !AppSessionUtils.statusOK()){
            return BusinessDTO.failBusiness("用户未审核");
        }
        int cnt = appUserApplyCompanyMapper.delete(new QueryWrapper<AppUserApplyCompany>().eq("company_id",webDTO.getCompanyId()).eq("app_user_id",AppSessionUtils.getUserId()));
        if( cnt == 0){
            return BusinessDTO.failBusiness("用户申请公司不存在");
        }
        return BusinessDTO.sucessBusiness(new HashMap<>(),"用户取消加入公司申请");
    }

    /**
     * 用户申请审批
     * @param webDTO
     * @return
     */
    public BusinessDTO<Object> userApplyApprove(UserApproveWebDTO webDTO){
        String applyUserId = StringUtils.trimToEmpty(webDTO.getUserId());
        if(StringUtils.isEmpty(applyUserId)) {
            return BusinessDTO.failBusiness("参数为空");
        }
        if( !webDTO.statusOK()){
            return BusinessDTO.failBusiness("请选择同意或拒绝");
        }
        if(!AppSessionUtils.isAdmin()){
            return BusinessDTO.failBusiness("非管理员无审批权限");
        }
        AppUserInfo applyUser = userInfoMapper.selectById(applyUserId);
        if(null == applyUser){
            return BusinessDTO.failBusiness("无此用户");
        }
        Integer applyUserStatus = applyUser.getStatus();
        if( !AppUserStatus.isApply(applyUserStatus) && !AppUserStatus.isOK(applyUserStatus)){
            return BusinessDTO.failBusiness("用户已冻结或注销");
        }
        String companyId = AppSessionUtils.getCompanyId();
        String applyCompanyId = companyId;
        if(AppUserStatus.isApply(applyUserStatus)){
            applyCompanyId = applyUser.getCompanyApply();
            if(StringUtils.isEmpty(applyCompanyId)){
                return BusinessDTO.failBusiness("用户注册未选择公司");
            }
            if( !applyCompanyId.equals(companyId)){
                return BusinessDTO.failBusiness("无审批权限");
            }
            AppUserInfo updUser = new AppUserInfo();
            updUser.setId(applyUserId);
            updUser.setCompanyApply("");
            updUser.setUpdateBy(AppSessionUtils.getUserName());
            updUser.setUpdateTime(new Date());
            userInfoMapper.updateById(updUser);
        } else {
            QueryWrapper wrapper = new QueryWrapper<AppUserApplyCompany>().eq("company_id",companyId).eq("app_user_id",applyUser.getId());
            if(ObjectUtils.isEmpty(appUserApplyCompanyMapper.selectList(wrapper))){
                return BusinessDTO.failBusiness("用户未申请公司");
            }
            appUserApplyCompanyMapper.delete(wrapper);
        }

        String dutiesStrings = webDTO.toDutiesStrings();
        if(StringUtils.isEmpty(dutiesStrings)){
            dutiesStrings = AppUserDutiesEnum.FEED.getDuties();
        }

        if(webDTO.refuseStatus() ){
            if(AppUserStatus.isApply(applyUserStatus)){
                userInfoMapper.deleteById(applyUserId);
            }
        }else {
            if(AppUserStatus.isOK(applyUserStatus)){
                List<AppUserCompanyEntity> userCompanyList = this.queryUserCompany(applyCompanyId, applyUserId);
                if (ObjectUtils.isNotEmpty(userCompanyList)) {
                    return BusinessDTO.failBusiness("用户已加入公司，无需申请");
                }
            }
            AppUserCompanyEntity userCompanyEntity = new AppUserCompanyEntity();
            userCompanyEntity.setAppUserId(applyUserId);
            userCompanyEntity.setCompanyId(applyCompanyId);
            userCompanyEntity.setIdentity(dutiesStrings);
            appUserCompanyMapper.insert(userCompanyEntity);

            appUserIdentityService.addUserIdentityList(applyCompanyId,applyUserId,dutiesStrings);

            AppUserInfo updUser = new AppUserInfo();
            updUser.setId(applyUserId);
            updUser.setStatus(AppUserStatus.OK.getStatus());
            updUser.setIdentity(dutiesStrings);
            updUser.setCompanys(this.queryUserCompanyIdStrings(applyCompanyId,applyUserId));
            userInfoMapper.updateById(updUser);
        }
        return BusinessDTO.sucessBusiness(new HashMap<>(),"用户申请审批");
    }

    /**
     * 设置用户身份
     * @param webDTO
     * @return
     */
    public BusinessDTO<Object> grantUserIdentity(UserApproveWebDTO webDTO){
        String applyUserId = StringUtils.trimToEmpty(webDTO.getUserId());
        String dutiesStrings = webDTO.toDutiesStrings();
        if(StringUtils.isAnyEmpty(applyUserId,dutiesStrings)) {
            return BusinessDTO.failBusiness("参数为空");
        }
        if(!AppSessionUtils.isAdmin()){
            return BusinessDTO.failBusiness("非管理员无授予身份权限");
        }
        AppUserInfo applyUser = userInfoMapper.selectById(applyUserId);
        if(null == applyUser){
            return BusinessDTO.failBusiness("无此用户");
        }
        String companyId = AppSessionUtils.getCompanyId();
        List<AppUserCompanyEntity> applyUserCompanyList = this.queryUserCompany(companyId,applyUserId);
        if(ObjectUtils.isNotEmpty(applyUserCompanyList)){
            for(AppUserCompanyEntity companyEntity : applyUserCompanyList){
                AppUserCompanyEntity updCompany = new AppUserCompanyEntity();
                updCompany.setId(companyEntity.getId());
                updCompany.setIdentity(dutiesStrings);
                appUserCompanyMapper.updateById(updCompany);
            }

            appUserIdentityService.updateUserIdentity(companyId,applyUserId,dutiesStrings);

            AppUserInfo updUser = new AppUserInfo();
            updUser.setId(applyUserId);
            updUser.setIdentity(dutiesStrings);
            updUser.setUpdateBy(AppSessionUtils.getUserName());
            updUser.setUpdateTime(new Date());
            userInfoMapper.updateById(updUser);
        }
        return BusinessDTO.sucessBusiness(new HashMap<>(),"设置用户身份");
    }

    /**
     * 将用户踢出公司
     * @param webDTO
     * @return
     */
    public BusinessDTO<Object> removeUserCompany(UserApproveWebDTO webDTO){
        String applyUserId = StringUtils.trimToEmpty(webDTO.getUserId());
        if(StringUtils.isAnyEmpty(applyUserId)) {
            return BusinessDTO.failBusiness("参数为空");
        }
        if(!AppSessionUtils.isAdmin()){
            return BusinessDTO.failBusiness("非管理员无权限");
        }
        AppUserInfo applyUser = userInfoMapper.selectById(applyUserId);
        if(null == applyUser){
            return BusinessDTO.failBusiness("无此用户");
        }
        String userCompanyId = applyUser.getCompanyId();
        String companyId = AppSessionUtils.getCompanyId();
        List<AppUserCompanyEntity> applyUserCompanyList = this.queryUserCompany(companyId,applyUserId);
        if(ObjectUtils.isEmpty(applyUserCompanyList)){
            return BusinessDTO.failBusiness("用户非公司员工");
        }
        List<String> ids = new ArrayList<>();
        for(AppUserCompanyEntity entity : applyUserCompanyList){
            if(AppUserDutiesEnum.isAdmin(entity.getIdentity())){
                return BusinessDTO.failBusiness("管理员不能踢出公司");
            }
            ids.add(entity.getId());
        }
        appUserCompanyMapper.deleteBatchIds(ids);
        applyUserCompanyList = this.queryUserCompany(null,applyUserId);
        if(ObjectUtils.isEmpty(applyUserCompanyList)){
            userInfoMapper.deleteById(applyUserId);
        }else {
            AppUserInfo updUser = new AppUserInfo();
            updUser.setId(applyUserId);
            if( companyId.equals(userCompanyId)){
                updUser.setCompanyId(applyUserCompanyList.get(0).getCompanyId());
            }
            updUser.setCompanys(getUserCompanyIdStrings(applyUserCompanyList));
            updUser.setUpdateBy(AppSessionUtils.getUserName());
            updUser.setUpdateTime(new Date());
            userInfoMapper.updateById(updUser);
        }
        return BusinessDTO.sucessBusiness(new HashMap<>(),"将用户踢出公司");
    }

    private String queryUserCompanyIdStrings(String companyId,String userId){
        return getUserCompanyIdStrings(this.queryUserCompany(companyId,userId));
        //return String.join(",",this.queryUserCompanyIds(companyId,userId));
    }
    private List<String> queryUserCompanyIds(String companyId,String userId){
        return getUserCompanyIds(this.queryUserCompany(companyId,userId));
    }
    private static String getUserCompanyIdStrings(List<AppUserCompanyEntity> entityList ){
        return String.join(",",getUserCompanyIds(entityList));
    }
    private static List<String> getUserCompanyIds(List<AppUserCompanyEntity> entityList ){
        List<String> ids = new ArrayList<>();
        if(ObjectUtils.isNotEmpty(entityList)){
            for (AppUserCompanyEntity entity : entityList) {
                ids.add(entity.getCompanyId());
            }
        }
        return ids;
    }
    private List<AppUserCompanyEntity> queryUserCompany(String companyId,String userId){
        QueryWrapper queryWrapper = new QueryWrapper<AppUserCompanyEntity>().eq("app_user_id",userId);
        if(StringUtils.isNotEmpty(companyId)){
            queryWrapper.eq("company_id",companyId);
        }
        queryWrapper.last("ORDER BY create_time");
        return appUserCompanyMapper.selectList(queryWrapper);
    }

    /**
     * 查询申请用户
     * @param webDTO
     * @return
     */
    private BusinessDTO<Object> queryApplyUserList(UserQueryInDTO webDTO){
        if(!AppSessionUtils.isAdmin()){
            return BusinessDTO.failBusiness("查询无权限");
        }
        webDTO.setCompanyId(AppSessionUtils.getCompanyId());
        webDTO.setUserId(AppSessionUtils.getUserId());
        webDTO.checkParam();

        Integer totalRow = userInfoMapper.queryApplyUserListTotal(webDTO);
        totalRow = null == totalRow? 0:totalRow;
        PageOutDTO<UserQueryOutDTO> outDTO = new PageOutDTO();
        outDTO.settingPage(webDTO,totalRow);
        if(totalRow > 0){
            List<UserQueryOutDTO> userList = userInfoMapper.queryApplyUserList(webDTO);
            outDTO.setList(userList);
        }
        if(ObjectUtils.isEmpty(outDTO.getList())){
            outDTO.setList(new ArrayList());
        }
        return BusinessDTO.sucessBusiness(outDTO,"查询申请用户 ");

    }


}
